//
//  WebServicUtils.swift
//  SmartCheckIn
//
//  Created by Cidy Chou on 2017/9/7.
//  Copyright © 2017年 CidyChou. All rights reserved.
//

import Foundation


class WebServiceUtils :NSObject,XMLParserDelegate {
    
    var mutableData : NSMutableData = NSMutableData()
    
    var currentElementName:String = ""
    var soapResult: String = "error"
    
    var soapResultList = Dictionary<String, String>()
    var array = [Dictionary<String, String>]()
    
    var methodName: String
    var paramsDict: [String: Any]? = nil
    var resultName: String
    var serverIP: String
    
    init(methodName: String, paramsDict : [String: Any]?,resultName : String,serverIP :String) { //  !! resultName要改为字典或者集合
        self.methodName = methodName
        if let dict = paramsDict {
            self.paramsDict = dict
        }
        self.resultName = resultName
        self.serverIP = serverIP
        
    }
    
//result-----><?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><sendVerificationCodeResponse xmlns="http://tempuri.org/"><sendVerificationCodeResult>7001</sendVerificationCodeResult></sendVerificationCodeResponse></soap:Body></soap:Envelope>
   
    ///最终版本
    func sendSMSResult(finish : @escaping (_ res:[String : String])->())  {
        //qos 优先级  .background 最低
        DispatchQueue.global(qos: .background).async {
            
            
            let URL = NSURL(string: self.serverIP)! //外网
            //let URL = NSURL(string: "http://www.digiin.net:8085/GaveService.asmx")! //外网
            //let URL = NSURL(string: "http://192.168.0.65:80/GaveService.asmx")! //内网
            //let URL = NSURL(string: "http://59.42.10.13:8085/GaveService.asmx")!
            let mutableURLRequest: NSMutableURLRequest = NSMutableURLRequest(url:URL as URL)

            let soapMsg: String = self.toSoapMessage(methodName: self.methodName, paramsDict: self.paramsDict)
            
            mutableURLRequest.setValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
            mutableURLRequest.setValue(String(soapMsg), forHTTPHeaderField: "Content-Length")
            mutableURLRequest.httpMethod = "POST"
            mutableURLRequest.httpBody = soapMsg.data(using: String.Encoding.utf8)

            let task = URLSession.shared.dataTask(with: mutableURLRequest as URLRequest) { (data, resp, error) in
                
                guard error == nil && data != nil else{
                    print("connection error or data is nill")
                    finish(self.soapResultList)
                    return 
                }
                
                if resp != nil {
                    self.mutableData.length = 0;
                }
                
                //let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
                self.mutableData.append(data!)
                
                // 开始解析
                let xmlParser = XMLParser(data: self.mutableData as Data)
                
                xmlParser.delegate = self
                xmlParser.parse()
                xmlParser.shouldResolveExternalEntities = true
            
                
                finish(self.soapResultList)
                
               // finish(self.soapResult)
                //DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {}
                
                
                
            }
            task.resume()
        }
        
    }

    
    ///最终版本
    func getServerResult(finish : @escaping (_ res:[Dictionary<String, String>])->())  {
        //qos 优先级  .background 最低
        DispatchQueue.global(qos: .background).async {
            
            let URL = NSURL(string: self.serverIP)! //外网
            let mutableURLRequest: NSMutableURLRequest = NSMutableURLRequest(url:URL as URL)
            
            let soapMsg: String = self.toSoapMessage(methodName: self.methodName, paramsDict: self.paramsDict)
            
            mutableURLRequest.setValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
            mutableURLRequest.setValue(String(soapMsg), forHTTPHeaderField: "Content-Length")
            mutableURLRequest.httpMethod = "POST"
            mutableURLRequest.httpBody = soapMsg.data(using: String.Encoding.utf8)
            
            let task = URLSession.shared.dataTask(with: mutableURLRequest as URLRequest) { (data, resp, error) in
                
                guard error == nil && data != nil else{
                    print("connection error or data is nill")
                    finish(self.array)
                    return
                }
                
                if resp != nil {
                    self.mutableData.length = 0;
                }
                self.mutableData.append(data!)
                
                // 开始解析
                let xmlParser = XMLParser(data: self.mutableData as Data)
                
                xmlParser.delegate = self
                xmlParser.parse()
                xmlParser.shouldResolveExternalEntities = true
        
                finish(self.array)
            }
            task.resume()
        }
    }
    
    
    //xml parser
    func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
        currentElementName = elementName
        print("elementName",elementName)
    }
    
    func parser(_ parser: XMLParser, foundCharacters string: String) {
       
        soapResultList[currentElementName] = string
        
//        if currentElementName.isEqual("ip"){
        if currentElementName.isEqual("ip") || currentElementName.isEqual("stuNum"){
        
            array.append(soapResultList)
            
        }
        
        print("soapResult\(soapResultList)")
        print("soapArray\(array)")
    }
    
    ///xml 拼接
    
    func toSoapMessage(methodName: String, paramsDict : [String: Any]?) -> String {
        var message: String = String()
        message += "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
        message += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
        message += "<soap:Body>"
        message += "<\(methodName) xmlns=\"http://tempuri.org/\">"//命名空间
        
        if paramsDict != nil{
        for (key, value) in paramsDict! {
            
            print("\(key): \(value)")
            message += "<\(key)>\(value)</\(key)>"  //后期添加遍历
        }
        }
        
        message += "</\(methodName)>"
        message += "</soap:Body>"
        message += "</soap:Envelope>"
        print("请求消息体： \(message)")
        return message
    }
    
    
//    func reqWebService(methodName: String, params: String ,paramValues: String) -> String{
//
//        //let URL = NSURL(string: "http://www.digiin.net:8085/GaveService.asmx")! //外网
//        //let URL = NSURL(string: "http://192.168.0.118:8011/GaveService.asmx")! //内网
//        let URL = NSURL(string: "http://59.42.10.13:8085/GaveService.asmx")!
//        let mutableURLRequest: NSMutableURLRequest = NSMutableURLRequest(url:URL as URL)
//
//        var smsDict : [String: String] = ["phone": "15590200211"]
//        let soapMsg: String = toSoapMessage(methodName: methodName, paramsDict: smsDict)
//
//        mutableURLRequest.setValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
//        mutableURLRequest.setValue(String(soapMsg), forHTTPHeaderField: "Content-Length")
//        mutableURLRequest.httpMethod = "POST"
//        mutableURLRequest.httpBody = soapMsg.data(using: String.Encoding.utf8)
//
//
//        let task = URLSession.shared.dataTask(with: mutableURLRequest as URLRequest) { (data, resp, error) in
//
//            guard error == nil && data != nil else{
//
//                print("connection error or data is nill")
//
//                return
//            }
//
//            if resp != nil {
//
//                self.mutableData.length = 0;
//
//            }
//
//            print("1--",self.mutableData)
//
//            let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
//            self.mutableData.append(data!)
//
//            let xmlParser = XMLParser(data: self.mutableData as Data)
//            xmlParser.delegate = self
//            xmlParser.parse()
//            xmlParser.shouldResolveExternalEntities = true
//            print("2--",dataString ?? "omg")
//            print("4--",self.mutableData)
//
//        }
//        task.resume()
//
//        return soapResult //后期改！～！～！
//
//        //        let task:URLSessionDataTask = URLSession.shared.dataTask(with: mutableURLRequest as URLRequest) { (data, response, error) in
//        //
//        //            let sResult = NSString.init(data: data!, encoding: String.Encoding.utf8.rawValue)
//        //
//        //            print("result----->\(sResult!)")
//        //            guard let data = data, error == nil else {
//        //                print("network error: \(error)")
//        //                return
//        //            }
//        //
//        //            let parser = XMLParser(data: data)
//        //            parser.delegate = self
//        //            guard parser.parse() else {
//        //                print("parsing error: \(parser.parserError)")
//        //                return
//        //            }
//        //
//        // if we've gotten here, update the UI
//
//        //            DispatchQueue.main.async {
//        //                if let fahrenheitValue = self.fahrenheitValue {
//        //                    print("\(fahrenheitValue)")
//        //                   // self.lblSonuc.text =
//        //                } else {
//        //                  print("No fahrenheit value found?!?")
//        //                    //self.lblSonuc.text = "No fahrenheit value found?!?"
//        //                }
//        //            }
//        //        }
//        //        task.resume()
//    }
}

